/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.TOOL;

/**
 *
 * @author Khôi
 */
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import jxl.Workbook;

import jxl.WorkbookSettings;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class WriteExcel {

	private WritableCellFormat timesBoldUnderline;
	private WritableCellFormat times;
	private String inputFile;

	public void setOutputFile(String inputFile) {
		this.inputFile = inputFile;
	}
	public void xuatExcel(JTable table, File file) throws IOException, WriteException {

		WorkbookSettings wbSettings = new WorkbookSettings();

		wbSettings.setLocale(new Locale("en", "EN"));

		WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
		workbook.createSheet("Report", 0);
		WritableSheet excelSheet = workbook.getSheet(0);

		WritableFont tieuDe = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE);
		// Define the cell format
		WritableFont binhThuong = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);

		TableModel model = table.getModel();

		times = new WritableCellFormat(tieuDe);// dinh dang tieu de
		times.setBorder(Border.ALL, BorderLineStyle.THIN);

		for (int i = 0; i < model.getColumnCount(); i++) {
			Label label;
			String s = model.getColumnName(i).toString();
			label = new Label(i, 0, s, times);
			excelSheet.addCell(label);
		}
		times = new WritableCellFormat(binhThuong);
		times.setBorder(Border.ALL, BorderLineStyle.THIN);

		for (int i = 0; i < model.getRowCount(); i++) {
			for (int j = 0; j < model.getColumnCount(); j++) {
				Label label;
				Object ob = model.getValueAt(i, j);
				if (ob instanceof Integer) {
					Integer s = (Integer) ob;
					Number number;
					number = new Number(j, i + 1, s, times);
					excelSheet.addCell(number);
				} else if (ob instanceof Double) {
					Double s = (Double) ob;
					Number number;
					number = new Number(j, i + 1, s, times);
					excelSheet.addCell(number);
				} else if (ob instanceof String) {

					String s = (String) ob;
					label = new Label(j, i + 1, s.toString(), times);
					excelSheet.addCell(label);


				} else if (ob instanceof Date) {
					Date s = (Date) ob;
					label = new Label(j, i + 1, s.toString(), times);
					excelSheet.addCell(label);
				}

			}

		}

		workbook.write();
		workbook.close();

	}

	


}
